package com.itdct.onflow.generator.template.web

import com.itdct.onflow.generator.base.BaseTemplate
import com.itdct.onflow.generator.config.GeneratorConfig
import com.itdct.onflow.generator.constant.GroupEnum
import com.itdct.onflow.generator.model.ClassModel
import com.itdct.onflow.generator.model.FieldModel

/**
 * @author Zhouwx
 * @date 2025/8/26 10:28:52
 * @version 1.0
 * @description
 */
abstract class BaseVueTemplate(classModel: ClassModel, generatorConfig: GeneratorConfig) : BaseTemplate(classModel, generatorConfig) {

    override fun belongGroup(): GroupEnum {
        return GroupEnum.FRONTEND
    }

    override fun getFolderFileName(): String {
//        val groupId = generatorConfig.groupId
//        if (groupId.isBlank()) {
//            throw RuntimeException("请填写groupId，否则前端文件无法生成")
//        }
//        val packageName = classModel.packageName
//        if (packageName.startsWith(groupId)) {
//            var path = packageName.substring(groupId.length)
//            if (path.startsWith(".")) {
//                path = path.substring(1)
//            }
//            path = path.replace(".", "/") + "/"
//            return path + restPath()
//        } else {
//            throw RuntimeException("类名的包名：${packageName}不以groupId：${groupId}开头，请检查配置情况")
//        }
        return getGroupIdPath(classModel.packageName) + restPath()
    }

    fun apiPath(): String {
        return getGroupIdPath(classModel.packageName) + classModel.className
    }

    fun getGroupIdPath(packageName: String): String {
        val groupId = generatorConfig.groupId
        if (groupId.isBlank()) {
            throw RuntimeException("请填写groupId，否则前端文件无法生成")
        }
//        val packageName = classModel.packageName
        if (packageName.startsWith(groupId)) {
            var path = packageName.substring(groupId.length)
            if (path.startsWith(".")) {
                path = path.substring(1)
            }
            path = path.replace(".", "/") + "/"
            return path
        } else {
            throw RuntimeException("类名的包名：${packageName}不以groupId：${groupId}开头，请检查配置情况")
        }
    }

    fun firstLetterUpper(str: String?): String {
        if (str == null) {
            return ""
        }
        return str.substring(0, 1).uppercase() + str.substring(1)
    }

    fun firstLetterLower(str: String?): String {
        if (str == null) {
            return ""
        }
        return str.substring(0, 1).lowercase() + str.substring(1)
    }

    fun selectFunctionImport(): String {
        return classModel.fieldList.filter {
            it.targetClass != null
        }.distinctBy {
            it.targetClass
        }.map {
            selectFunctionImportContent(it)
        }.joinToString("\n")
    }

    fun selectFunctionImportContent(it: FieldModel): String {
        if (it.targetClass == null) {
            return ""
        }
        return """
|import { select${it.targetClassName}${firstLetterUpper(it.targetFieldName)}ListApi } from '@/api/${getTargetClassApiPath(it)}'
        """.trimMargin()
    }

    fun getTargetClassApiPath(it: FieldModel): String {
        val targetKClass = it.targetClass ?: return ""
        val clazz = targetKClass.java
        var packageName = clazz.packageName
        if (packageName.endsWith(".entity")) {
            packageName = packageName.substring(0, packageName.length - 7)
        }
        val groupIdPath = getGroupIdPath(packageName)
        val className = clazz.simpleName.replace("Entity", "")
        return groupIdPath + className
    }

    fun renderDictFunctions(): String {
        return classModel.fieldList.filter {
            it.dictCode.isNotBlank()
        }.distinctBy {
            it.dictCode
        }.map {
            selectDictContent(it)
        }.joinToString("\n") + "\n"
    }

    fun selectDictContent(it: FieldModel): String {
        return """
const ${it.name}Options = ref<Array<KeyLabelValueVo>>([])
const get${it.nameBigCamel} = async () => {
  const res = await sysDictChooseListApi('${it.dictCode}')
  ${it.name}Options.value = res.data
}
get${it.nameBigCamel}()
        """.trimIndent()
    }

    fun renderSelectFunctions(): String {
        return classModel.fieldList.filter {
            it.targetClass != null
        }.distinctBy {
            it.targetClass
        }.map {
            selectFunctionContent(it)
        }.joinToString("\n") + "\n"
    }

    fun selectFunctionContent(it: FieldModel): String {
        if (it.targetClass == null) {
            return ""
        }
        return """
const ${firstLetterLower(it.targetClassName)}${firstLetterUpper(it.targetFieldName)}List = ref<Array<KeyLabelValueVo>>([])
const get${it.targetClassName}${firstLetterUpper(it.targetFieldName)}List = async () => {
  const res = await select${it.targetClassName}${firstLetterUpper(it.targetFieldName)}ListApi({})
  ${firstLetterLower(it.targetClassName)}${firstLetterUpper(it.targetFieldName)}List.value = res.data
}
get${it.targetClassName}${firstLetterUpper(it.targetFieldName)}List()
        """.trimIndent()
    }

    fun targetClassIdLabel(fieldModel: FieldModel): String {
        if (fieldModel.targetClass == null) {
            return fieldModel.comment
        } else {
            val comment = fieldModel.comment.lowercase()
            if (comment.endsWith("id")) {
                return comment.substring(0, comment.length - 2)
            } else {
                return comment
            }
        }
    }


    abstract fun restPath(): String
}